package com.linjiang;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOSelectorServer {

    public static void main(String[] args) throws IOException {
        //创建 NIO ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8081));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //打开Selector(多路复用器)处理Channel 即创建epoll
        Selector selector = Selector.open();
        //把ServerSocketChannel注册到selector上， 并且selector 对客户端accept连接操作感兴趣
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("nio启动成功");
        while (true){
            //阻塞等待需要处理的事件发生，让出cpu使用权
            selector.select();

            //获取selector中注册的全部事件的SelectorKey的实例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            //遍历 SelectorKey 对事件进行处理
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //如果是OP_ACCEPT事件，则进行连接获取和事件注册
                if (key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = server.accept();
                    if (socketChannel != null){
                        //设置socketChannel为非阻塞
                        socketChannel.configureBlocking(false);
                        //这里只注册了读事件，如果需要给客户端发生数据可以注册写事件
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        System.out.println(socketChannel+"连接成功");
                    }
                } else if (key.isReadable()){
                    //如果是SelectionKey.OP_READ 事件，则进行读取和打印
                    SocketChannel SocketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(10);
                    int read = SocketChannel.read(byteBuffer);
                    if (read > 0){
                        System.out.println(SocketChannel+"接收到数据："+new String(byteBuffer.array()));
                    }else if (read == -1){
                        //如果客户端断开，把socket从集合中去掉
                        iterator.remove();
                        System.out.println("客户端断开连接");
                    }
                }
            }
        }
    }
}
